#include <wm.h>
#include <gato/surface.h>
#include <gato/render.h>
#include <gato/svg.h>
#include <string.h>
#include <stdio.h>
#include <malloc.h>
#include <types.h>
#include <stdlib.h>
#include <ginkgo/class.h>
#include <plutovg.h>
#include <plutosvg.h>

#define WINDOW_W 400
#define WINDOW_H 300

static int TestSVG(surface_t *base)
{
    plutovg_surface_t *surface = plutosvg_load_from_file("/camera.svg", NULL, 0, 0, 96.0);
    if (surface == NULL)
    {
        printf("Load failed\n");
        return -1;
    }

    surface_t *s = surface_alloc_wrap(plutovg_surface_get_data(surface), plutovg_surface_get_width(surface), plutovg_surface_get_height(surface));
    surface_blit(base, s, 0, 0);
    free(s);
    plutovg_surface_destroy(surface);
    return 0;
}

static int TestVG(char *data, int width, int height)
{
    plutovg_surface_t *surface = plutovg_surface_create_for_data(data, width, height, width * sizeof(color_t));
    plutovg_t *pluto = plutovg_create(surface);

    double center_x = width * 0.5;
    double center_y = height * 0.5;
    double face_radius = 70;
    double eye_radius = 10;
    double mouth_radius = 50;
    double eye_offset_x = 25;
    double eye_offset_y = 20;
    double eye_x = center_x - eye_offset_x;
    double eye_y = center_y - eye_offset_y;

    const double pi = 3.14159265358979323846;

    plutovg_save(pluto);
    plutovg_arc(pluto, center_x, center_y, face_radius, 0, 2 * pi, 0);
    plutovg_set_source_rgb(pluto, 1, 1, 0);
    plutovg_fill_preserve(pluto);
    plutovg_set_source_rgb(pluto, 0, 0, 0);
    plutovg_set_line_width(pluto, 5);
    plutovg_stroke(pluto);
    plutovg_restore(pluto);

    plutovg_save(pluto);
    plutovg_arc(pluto, eye_x, eye_y, eye_radius, 0, 2 * pi, 0);
    plutovg_arc(pluto, center_x + eye_offset_x, eye_y, eye_radius, 0, 2 * pi, 0);
    plutovg_fill(pluto);
    plutovg_restore(pluto);

    plutovg_save(pluto);
    plutovg_arc(pluto, center_x, center_y, mouth_radius, 0, pi, 0);
    plutovg_set_line_width(pluto, 5);
    plutovg_stroke(pluto);
    plutovg_restore(pluto);

    // plutovg_surface_write_to_png(surface, "smiley.png");
    plutovg_surface_destroy(surface);
    plutovg_destroy(pluto);

    return 0;
}

int main(int argc, char **argv)
{
    do_wm_init();
    window_t *win = wm_window_create(100, 100, WINDOW_W, WINDOW_H, RGB(0xffffff));
    wm_window_event_mask_set(win, WM_ROOT_ABS_EVENT);
    wm_window_show(win);

    TestVG(win->connect.surface->pixels,
           win->connect.surface->width,
           win->connect.surface->height);
    TestSVG(win->connect.surface);
    wm_window_update(win);
    return 0;
}